package org.jeecg.modules.demo.crm.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.jeecg.common.util.Md5Util;
import org.jeecg.modules.demo.crm.email.EmailUtils;
import org.jeecg.modules.demo.crm.entity.CEmail;
import org.jeecg.modules.demo.crm.entity.CProjectApplication;
import org.jeecg.modules.demo.crm.entity.CSubProject;
import org.jeecg.modules.demo.crm.mapper.CEmailMapper;
import org.jeecg.modules.demo.crm.mapper.CProjectApplicationMapper;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.ICEmailService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 邮件
 * @Author: jeecg-boot
 * @Date: 2025-07-04
 * @Version: V1.0
 */
@Service
public class CEmailServiceImpl extends ServiceImpl<CEmailMapper, CEmail> implements ICEmailService {
    @Autowired
    private JavaMailSender qqMailSender;
    @Autowired
    private JavaMailSender neteaseMailSender;

    @Value("${qq.mail.username}")
    private String qqFrom;

    @Value("${netease.mail.username}")
    private String neteaseFrom;

    @Autowired
    private CEmailMapper cemailMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private CSubProjectMapper cSubProjectMapper;

    @Autowired
    private CProjectApplicationMapper projectApplicationMapper;



    @Override
    public void taskEMail() {
        List<CEmail> cEmails = cemailMapper.taskEMail();
        for (CEmail cEmail : cEmails) {
            try {
                try {
                    //sendQQEmail(cEmail);
                    sendNeteaseEmail(cEmail);
                    cEmail.setStatus("完成");
                    cEmail.setCode("200");
                    cEmail.setMsg("完成");
                } catch (Exception e) {
                    e.printStackTrace();
                    cEmail.setStatus("失败");
                    cEmail.setCode("-1");
                    cEmail.setMsg(e.getMessage());
                }
                cEmail.setSendTime(new Date());
                cemailMapper.updateById(cEmail);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    @Override
    public String addTaskEmail(String userId, String subject, String content, String attachmentUrl) {
        SysUser user = sysUserService.getById(userId);
        String userEmail ="";
        String status ="待发送";
        String code ="0";
        String msg ="";
        if(user != null && StringUtils.isNoneEmpty(user.getEmail())){
             userEmail =user.getEmail();
        }else {
            status ="失败";
            code = "-1";
            msg ="用户不存在，或邮箱地址不存在";
        }
        String dataKey = Md5Util.md5Encode(subject + "-" + attachmentUrl + " - " + userId,"utf-8");
        CEmail flag = cemailMapper.findByDataKey(dataKey);
        if(flag == null){
            CEmail cemail = CEmail.builder()
                    .userEmail(userEmail)
                    .subject(subject)
                    .userId(userId)
                    .content(content)
                    .attachmentUrl(attachmentUrl)
                    .status(status)
                    .msg(msg)
                    .code(code)
                    .dataKey(dataKey)
                    .build();
            cemailMapper.insert(cemail);
            return cemail.getId();
        }
        return null;
    }


    @Override
    public void sendQQEmail(CEmail cEmail) {
        sendEmailUtils(qqFrom,  cEmail);
    }

    @Override
    public void sendNeteaseEmail(CEmail cEmail) {
        sendEmailUtils(neteaseFrom, cEmail);
    }



    public void sendEmailUtils(String from, CEmail cEmail) {
        try {
            MimeMessage mimeMessage = neteaseMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // 指定编码为 UTF-8

            helper.setFrom(from);
            helper.setTo(cEmail.getUserEmail());
            helper.setSubject(cEmail.getSubject());

            // 增加抄送
            if (StringUtils.isNotEmpty(cEmail.getAttachedMaill())) {
                // 支持多个抄送人, 逗号分隔
                String[] ccArray = cEmail.getAttachedMaill().split(",");
                helper.setCc(ccArray);
            }

            if (StringUtils.isNoneEmpty(cEmail.getSubject()) && StringUtils.isNoneEmpty(cEmail.getContent())) {
                // 读取模板文件并替换占位符
                String htmlContent = EmailUtils.getHtmlContent(cEmail.getSubject(), cEmail.getContent());
                helper.setText(htmlContent, true);
            }
            if(StringUtils.isNoneEmpty(cEmail.getAttachmentUrl()) && cEmail.getAttachmentUrl().length() > 0){
                String[] fileUrlS = cEmail.getAttachmentUrl().split(",");
                for (String fileUrl : fileUrlS) {
                    if(StringUtils.isNotEmpty(fileUrl) && fileUrl.length() > 5){
                        File attachmentFile = EmailUtils.downloadFile(fileUrl);
                        if (attachmentFile != null) {
                            FileSystemResource file = new FileSystemResource(attachmentFile);

                            String fileName = file.getFilename();
                            try {
                                // 获取文件扩展名
                                String fullName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
                                String ext = fullName.substring(fullName.lastIndexOf('.'));
                                // 截取前64个字符（不含扩展名）
                                String baseName = fullName.substring(0, fullName.lastIndexOf('.'));
                                String truncatedName = baseName.length() > 46 ? baseName.substring(0, 45) : baseName;
                                // 拼接扩展名
                                fileName = truncatedName + ext;
                            } catch (Exception e) {
                               // throw new RuntimeException(e);
                            }
                            helper.addAttachment(fileName, file);
                        }
                    }

                }
            }
            neteaseMailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 查询待报价的子项目
     */
    @Override
    public void subProjectQuote() {
        //根据用户查询
        List<CSubProject> subProjectList = cSubProjectMapper.subProjectQuote();
        // 根据userId对subProjectList进行归类
        Map<String, List<CSubProject>> subProjectMap = subProjectList.stream()
                .filter(subProject -> subProject.getUserId() != null)
                .collect(Collectors.groupingBy(CSubProject::getUserId));
        for(String userId : subProjectMap.keySet()){
            List<CSubProject> cSubProjectList = subProjectMap.get(userId);
            if(cSubProjectList.size() == 1){
                CSubProject cSubProject = cSubProjectList.get(0);
                CProjectApplication cProjectApplication = projectApplicationMapper.selectById(cSubProject.getProjectId());

                String subject = cSubProject.getSubProjectName() + "---报价提醒";
                StringBuilder content = new StringBuilder();
                content.append("<p><h1>" + cProjectApplication.getProjectName() + "--" + cSubProject.getSubProjectName() + "</h1></p>");
                content.append("<p>简介：" + cSubProject.getSubProjectDescription() + "</p>");
                content.append("<p>项目地址：" + cSubProject.getAddress() + "</p>");
                content.append("<hr>");
                content.append("<br/>");
                addTaskEmail(userId, subject, content.toString(), cSubProject.getAttachmentUrl());
            }else{
                //合并发送
                String subject = cSubProjectList.get(0).getSubProjectName() + "...等共 "+cSubProjectList.size()+"个项目需要报价 ---报价提醒";
                StringBuilder content = new StringBuilder();
                StringBuilder attachmentUrl = new StringBuilder();
                for(CSubProject cSubProject : cSubProjectList){
                    CProjectApplication cProjectApplication = projectApplicationMapper.selectById(cSubProject.getProjectId());
                    if (cProjectApplication != null){
                        if(cProjectApplication.getProjectName() != null && cProjectApplication.getProjectName().length() > 0){
                            content.append("<p><h1>" + cProjectApplication.getProjectName() + "--" + cSubProject.getSubProjectName() + "</h1></p>");
                        }
                        content.append("<p>简介：" + cSubProject.getSubProjectDescription() + "</p>");
                        content.append("<p>项目地址：" + cSubProject.getAddress() + "</p>");
                        content.append("<hr>");
                        content.append("<br/>");
                        attachmentUrl.append(cSubProject.getAttachmentUrl()+",");
                    }else {
                        break;
                    }
                }
                addTaskEmail(userId, subject, content.toString(), attachmentUrl.toString());
            }
        }

    }
}
